package com.example.core.utils;

import org.jgroups.Address;
import org.jgroups.JChannel;
import org.jgroups.util.UUID;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author chentao
 * @version 1.0
 * @description: TODO
 * @date 2025/2/22 下午6:46
 */
public class RandomUtils {

    /****
     * 获取一个随机数
     * @param max
     * @return
     */
    public static int getRandomInt(int max) {
        Random random = new Random();
        return random.nextInt(max);
    }

    /****
     * 随机获取一个客户端的地址.
     * @param addresses
     * @return
     */
    public static Address getAddress(List<Address> addresses) throws Exception {
        return addresses.get(getRandomInt(addresses.size()));
    }

    /****
     * 获取随机地址，排除自己
     * @param channel
     * @return
     */
    public static Address getAddress(JChannel channel) throws Exception {
        Address meAddress = channel.getAddress();
        List<Address> addresses = new ArrayList<Address>();
        for (Address address : channel.getView()) {
            if (address instanceof UUID && !(meAddress.toString().equalsIgnoreCase(address.toString()))) {
                addresses.add(address);
            }
        }
        return getAddress(addresses);
    }
}

